/**
 * Created by yang on 15/1/29.
 */
var express = require('express');
var child_process = require('child_process');
var app = express();

var port = process.argv[2] || 3021;


var bodyParser = require('body-parser');
var methodOverride = require('method-override');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());

function autoPull(callback){
    var pushReportStr = '';
    child = child_process.spawn('sh',['git_pull.sh']);
    child.stdout.setEncoding('utf8');
    child.stdout.on('data', function(data) {
        console.log(data);
        pushReportStr += data;
    });
    child.stdout.on('close',function(data){
        callback(pushReportStr);
    });
}

app.post('/oschina', function (req, res) {
    console.log(req.body);
    var hook = JSON.parse(req.body.hook);
    console.log('hook',hook);
    console.log('password',hook.password);
    if(hook.password == 'your_password'){
        console.log('auto pulling ...');
        autoPull(function(pushReturnStr){
            console.log('auto update success!');
        });
    }
    res.json({ok:true});
});

var server = app.listen(port, function () {

    var host = server.address().address;
    var port = server.address().port;

    console.log('zhudelab push_hook listening at http://%s:%s', host, port)

});
